package com.zyz.forum.controller;

import com.zyz.forum.common.AppResult;
import com.zyz.forum.common.ResultCode;
import com.zyz.forum.config.AppConfig;
import com.zyz.forum.dao.ArticleMapper;
import com.zyz.forum.model.Article;
import com.zyz.forum.model.Board;
import com.zyz.forum.model.User;
import com.zyz.forum.service.IArticleService;
import com.zyz.forum.service.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(tags = "帖子接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IBoardService boardService;

    @Resource
    private IArticleService articleService;
    @Resource
    private ArticleMapper articleMapper;

    @ApiOperation("发布帖子")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("板块ID") @RequestParam("boardId") @NonNull Long boardId,
                            @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("文章内容") @RequestParam("content") @NonNull String content) {
        // 校验用户是否已被禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_ID);
        if (user.getState() == 1) {
            // 用户已被禁言
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 板块校验，确认板块Id的正确性（该板块存在）
        Board board = boardService.selectById(boardId);
        if (board == null || board.getState() == 1 || board.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString() + " 板块id = " + boardId);
            return AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS);
        }
        // 写入文章信息
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setUserId(user.getId());
        article.setBoardId(board.getId());
        article.setVisitCount(0);
        article.setReplyCount(0);
        article.setLikeCount(0);
        article.setState((byte) 0);
        article.setDeleteState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);
        // 新增文章信息
        articleService.create(article);
        return AppResult.success();
    }

    @ApiOperation("获取帖子列表")
    @PostMapping("/getListByBoardId")
    public AppResult<List<Article>> getListByBlogId(@ApiParam("板块id") @RequestParam(value = "boardId",required = false) Long boardId) {
        List<Article> articles = null;
        if (boardId == null) {
            // 查询所有板块内容
            articles = articleService.selectAll();
        } else {
            // 根据板块id查询帖子
            articles = articleService.selectInfoByBoardId(boardId);
        }
        // 判断是否为空
        if (articles == null) {
            articles = new ArrayList<>();
        }
        // 返回结果
        return AppResult.success(articles);
    }

    @ApiOperation("根据id获取帖子信息")
    @GetMapping("/getDetails")
    public AppResult<Article> getDetails(HttpServletRequest request,
                                         @ApiParam("帖子id") @RequestParam("id") @NonNull Long id) {
        // 拿到session
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_ID);
        // 调用service层
        Article article = articleService.selectDetailById(id);
        if (article == null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 判断用户是否是文章作者
        if (user.getId().equals(article.getUserId())) {
            article.setIsOwn(true);
        }
        // 返回结果
        return AppResult.success(article);
    }

    @ApiOperation("修改帖子内容")
    @PostMapping("/updateArticle")
    public AppResult updateArticle(HttpServletRequest request,
                                   @ApiParam("帖子id") @RequestParam("id") @NonNull Long id,
                                   @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                                   @ApiParam("文章内容") @RequestParam("content") @NonNull String content) {
        // 获取session
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_ID);
        // 判断用户是否被禁言
        if (user.getState() == 1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 判断帖子状态
        Article article = articleService.selectById(id);
        if (article == null || article.getState() == 1 || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS_OR_NO_MODIFICATION.toString());
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS_OR_NO_MODIFICATION);
        }
        // 判断是否是帖子用户
        if (!article.getUserId().equals(user.getId())) {
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 修改帖子
        articleService.updateArticle(id,title,content);
        // 修改成功
        log.info("帖子修改成功 Article id = " + id + " user id = " + user.getId());
        return AppResult.success();
    }

    @ApiOperation("帖子点赞数+1")
    @PostMapping("/thumbsUpById")
    public AppResult thumbsUpById(HttpServletRequest request ,
                                  @ApiParam("帖子id") @RequestParam("id") @NonNull Long id) {
        // 获取用户情况
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_ID);
        if (user.getState() == 1) {
            // 用户已禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 调用service层
        articleService.thumbsUpById(id);
        // 返回结果
        return AppResult.success();
    }

    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @ApiParam("帖子id") @RequestParam("id") @NonNull Long id) {
        // 获取session 判断用户状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_ID);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 查询帖子详情
        Article article = articleService.selectById(id);
        if (article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 查询是否是作者
        if (!user.getId().equals(article.getUserId())) {
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        // 进行删除操作
        articleService.deleteById(id);
        // 删除成功
        log.info("帖子删除成功 Article id = " + id + " user id = " + user.getId());
        return AppResult.success();
    }

    @ApiOperation("根据用户id查询帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                                   @ApiParam("用户id") @RequestParam(value = "userId" , required = false) Long userId) {
        // 判断如果userId为空则通过session获取userId
        if (userId == null) {
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION_ID);
            userId = user.getId();
        }
        // 调用service层
        List<Article> articles = articleService.selectByUserId(userId);
        return AppResult.success(articles);
    }
}
